package com.iasku.loadimg;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.os.Handler;
import android.os.Message;

public class StreamService {
	public static void readData(InputStream in,OutputStream out){
		if(in!=null&&out!=null){
			try{
				BufferedInputStream bis = new BufferedInputStream(in);
				BufferedOutputStream bos = new BufferedOutputStream(out);
				int len = -1;
				byte[] buffer = new byte[1024];
				while((len=bis.read(buffer))!=-1){
					bos.write(buffer, 0, len);
					bos.flush();
				}
				bis.close();
				out.close();
				bis.close();
				in.close();
			}catch(IOException e){
				e.printStackTrace();
			}
		}
	}
	
	
	public static void saveTo(InputStream in, String savePath) {
		if (in != null && savePath != null) {
			try {
				File file = new File(savePath);
				if (!file.getParentFile().exists()) {
					file.getParentFile().mkdirs();
				}

				FileOutputStream out = new FileOutputStream(file);
				readData(in, out);
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	public void readData(InputStream in, OutputStream out, Handler handler,long totalLength) {
		if (in != null && out != null) {
			try {
				BufferedInputStream bis = new BufferedInputStream(in);
				BufferedOutputStream bos = new BufferedOutputStream(out);
				int len = -1;
				int loadedLength = 0;
				int count = 0;
				byte[] buffer = new byte[1024];
				while ((len = bis.read(buffer)) != -1) {
					count+=len;
					bos.write(buffer, 0, len);
					bos.flush();
					if ( handler != null) {
						loadedLength = (int) (((float) count /totalLength) * 100);
						Message msg = Message.obtain();
						msg.what = 1000;
						msg.arg1 = loadedLength;
						handler.sendMessage(msg);
					}
				}
				bos.close();
				out.close();
				bis.close();
				in.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		}
	
	public void save(InputStream in, String savePath, Handler handler,long totalLength) {
		if (in != null && savePath != null) {
			try {
				File file = new File(savePath);
				if (!file.getParentFile().exists()) {
					file.getParentFile().mkdirs();
				}

				FileOutputStream out = new FileOutputStream(file);
				readData(in, out, handler,totalLength);
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
